# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from .base import BaseClassificationHead
from utils import CLASSIFICATION_HEADS
from sklearn.linear_model import LogisticRegression
import numpy as np


@CLASSIFICATION_HEADS.register_module("mteb_lr")
class MtebLR(BaseClassificationHead):
    def __init__(self, label_name, head_params=None):
        super().__init__(label_name, head_params)
        self.model = LogisticRegression(**self.head_params)

    def train(self, datasets: dict):
        self.logger.info(f"start train {self.model_name}")
        X_train, y_train = None, []
        for label, data in datasets.items():
            y_train += [label] * len(data.values())
            if X_train is None:
                X_train = np.array(list(data.values()))
            else:
                X_train = np.concatenate([X_train, np.array(list(data.values()))], axis=0)
        self.model.fit(X_train, y_train)
        self.logger.info(f"train {self.model_name} successfully")

    def infer(self, datasets):
        self.logger.info(f"start infer {self.model_name}")
        infer_result = {}
        for label, data in datasets.items():
            X_test = np.array(list(data.values()))
            y_pred_proba = self.model.predict_proba(X_test)
            infer_result[label] = dict(zip(data.keys(), y_pred_proba))
        self.logger.info(f"infer {self.model_name} finished")
        return infer_result
